import store from '../store/index.js'
import {request} from './http.js'


/**
 * 判断用户是否具有操作权限
 */
export const hasPermisson = (tag = '') => {
	if (store.state.currentBookUserId == store.getters.id) {
		console.info('账本管理员操作，允许操作')
		return true
	}
	
	if (!tag) {
		console.error(`非法的tag${tag}`)
		return false
	}
	
	const rights = store.state.rightMenus
	const right = rights.find(item => item.tag == tag)
	if (!right) {
		console.error(`无效的tag[${tag}]`)
		return false
	}
	
	console.log('store.state.userRightMenus', store.state.userRightMenus);
	
	const idx = store.state.userRightMenus.indexOf(right.id)
	return idx > -1
}

export const setUserPermission = (bookId) => {
	return new Promise((resolve, reject) => {
		const uid = store.getters.id
		if (uid && bookId) {
			request({
				url: `/user/${uid}/${bookId}/right`
			}).then(res => {
				console.log('res.data.right', res.data.right);
				store.commit('setUserRightMenus', res.data.right)
				resolve()
			})
		} else {
			console.log(`非法的userId[${uid}]或者bookId[${bookId}]`)
			reject()
		}
	})
}

export const isAdmin = () => {
	return store.state.currentBookUserId == store.getters.id
}

// export const hasPermisson = () => {
// 	if (store.state.currentBookUserId != store.getters.id) {
// 		uni.showToast({
// 			title: '没有权限',
// 			icon: 'error'
// 		})
// 		return false
// 	}
// 	return true
// }